//
//  NetworkTools.swift
//  MyBlog
//
//  Created by lvtienan on 15/7/30.
//  Copyright © 2015年 ltn. All rights reserved.
//

import UIKit
import AFNetworking

// 错误的类别标记
private let HMErrorDomainName = "com.itheiman.error.network"

// 网络访问错误信息
private enum HMNetworkError: Int {
    case emptyDataError = -1
    case emptyTokenEror = -2
    
    private var errorDescription: String {
        switch self {
        case .emptyDataError: return "空数据"
        case .emptyTokenEror: return "Token 为空"
        }
    }
    
    private func error() -> NSError {
        return NSError(domain: HMErrorDomainName, code: rawValue, userInfo: [HMErrorDomainName: errorDescription])
    }
}

private enum HMNetworkMethod: String {
    case GET = "GET"
    case POST = "POST"
}

/// 网络访问工具
class NetworkTools: AFHTTPSessionManager {
    
    // MARK - OAuth 授权
    private let clientId = "1198707931"
    private let appSecret = "69112be77a2234fea28ef92eeba015f3"
    // 回调地址
    let redirectUri = "http://www.baidu.com"
    


    // 单例
    static let sharedNetworkTools: NetworkTools = {
        let instance = NetworkTools(baseURL: NSURL(string: "https://api.weibo.com/")!)
        // 设置数据解析数据类型
        //self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
        instance.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        
        return instance
    }()
    
    /// MARK: - 加载微博数据

    func loadStatus(finished:HMNetFinishedCallBack) {
        // 判断 token 是否存在
        if UserAccount.loadAccount()?.access_token == nil {
            // 错误回调, token 为空
            let error = HMNetworkError.emptyTokenEror.error()
            print(error)
        }
        
        // https://api.weibo.com/2/statuses/home_timeline.json
        let urlString = "/2/statuses/home_timeline.json"
        let params: [String: AnyObject] = ["access_token":UserAccount.loadAccount()!.access_token!]
        request(HMNetworkMethod.GET, urlString: urlString, params: params, finished: finished)
    }
    
    /// 加载用户数据
    func loaduserInfo(uid: String, finished:HMNetFinishedCallBack) {
        if UserAccount.loadAccount()?.access_token == nil {
            let error = HMNetworkError.emptyTokenEror.error()
            print(error)
            
            finished(result: nil, error: error)
            return
        }
        
        let urlString = "2/users/show.json"
        let params: [String: AnyObject] = ["access_token": UserAccount.loadAccount()!.access_token!, "uid": uid]
//        requestGET(urlString, params: params) { (result, error) -> () in
//            print(result)
//        }
       // requestGET(urlString, params: params, finished: finished)
        request(HMNetworkMethod.GET, urlString: urlString, params: params, finished: finished)
    }
    
    
    /// 返回 OAuth 的授权地址.
    ///
    /// - returns: 用户通过微博帐号可以访问我们的应用程序
    func oauthUrl() -> NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
    
    // 加载 token
    //JSON 这里解析出来是字典
    //         {
    //            "access_token" = "2.009KYHdDtgeH_B813e4e0ea50kd_do";
    //            "expires_in" = 157679999;
    //            "remind_in" = 157679999;
    //            uid = 3326475240;
    //        }
    func  loadAccessToken(code: String, finished: HMNetFinishedCallBack) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":clientId,
            "client_secret":appSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirectUri]

//
       // requestPOST(urlString, params: params, finished: finished)
        request(HMNetworkMethod.POST, urlString: urlString, params: params, finished: finished)
    }
    
    
    // MARK: - 封装 AFN 网络方法
    typealias HMNetFinishedCallBack = (result: [String: AnyObject]?, error:NSError?) -> ()
    
    
    private func request(method: HMNetworkMethod,urlString: String, params: [String: AnyObject], finished: HMNetFinishedCallBack) {
        
        // 1. 定义成功的闭包
        let successCallBack: (NSURLSessionDataTask!, AnyObject!) -> Void = { (_, JSON) -> Void in
            
            if let result = JSON as? [String: AnyObject] {
                finished(result: result, error: nil)
            } else {
                // 没有错误同时没有结果
                print("没有错误同时没有结果")
                
                finished(result: nil, error: HMNetworkError.emptyDataError.error())
            }
        }

        // 2. 定义失败的闭包
        
        let failedCallBack: (NSURLSessionDataTask!,NSError!) -> Void = { (_, error) -> Void in
            print(error)
            finished(result: nil, error: error)
        }
        
        // 根据 method 选择方法
        switch method {
        case .GET:
            GET(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        case .POST:
            POST(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        }
    }
}




